<template>
  <div class="anniversary-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <el-button class="back-btn" circle @click="goHome">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>🎉 我们的纪念日</h1>
      <el-button class="add-btn" circle @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
      </el-button>
    </div>

    <!-- 即将到来的纪念日 -->
    <div class="upcoming-section" v-if="upcomingList.length > 0">
      <h3 class="section-title">⏰ 即将到来（7天内）</h3>
      <div class="upcoming-cards">
        <div
          v-for="item in upcomingList"
          :key="'upcoming-' + item.id"
          class="anniversary-card upcoming"
        >
          <div class="card-icon">🎊</div>
          <div class="card-content">
            <h4 class="card-title">{{ item.title }}</h4>
            <p class="card-date">{{ formatDate(item.date) }}</p>
            <p class="countdown">{{ getCountdown(item.date, item.isAnnual) }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 所有纪念日 -->
    <div class="all-section">
      <h3 class="section-title">📅 所有纪念日</h3>

      <div v-loading="loading" class="anniversary-list">
        <div v-if="anniversaryList.length === 0" class="empty-state">
          <el-empty description="还没有添加纪念日哦" />
        </div>

        <div v-else class="anniversary-grid">
          <div
            v-for="item in anniversaryList"
            :key="item.id"
            class="anniversary-card"
          >
            <div class="card-header">
              <div class="card-icon">{{ getIcon(item.title) }}</div>
              <div class="card-actions">
                <el-button
                  type="primary"
                  size="small"
                  circle
                  @click="showEditDialog(item)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  circle
                  @click="handleDelete(item.id)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>

            <div class="card-content">
              <h4 class="card-title">{{ item.title }}</h4>
              <p class="card-date">{{ formatDate(item.date) }}</p>
              <p class="card-type">
                <el-tag :type="item.isAnnual ? 'success' : 'info'" size="small">
                  {{ item.isAnnual ? '每年重复' : '仅一次' }}
                </el-tag>
              </p>
              <p class="countdown">{{ getCountdown(item.date, item.isAnnual) }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑纪念日对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑纪念日' : '添加纪念日'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="纪念日名称" prop="title">
          <el-input
            v-model="form.title"
            placeholder="例如：恋爱纪念日、生日等"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="重复方式">
          <el-radio-group v-model="form.isAnnual">
            <el-radio :label="true">每年重复</el-radio>
            <el-radio :label="false">仅一次</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="quick-presets">
          <p class="preset-title">💡 快速选择：</p>
          <div class="preset-buttons">
            <el-button size="small" @click="usePreset('恋爱纪念日', true)">恋爱纪念日</el-button>
            <el-button size="small" @click="usePreset('TA的生日', true)">TA的生日</el-button>
            <el-button size="small" @click="usePreset('我的生日', true)">我的生日</el-button>
            <el-button size="small" @click="usePreset('初次见面', true)">初次见面</el-button>
            <el-button size="small" @click="usePreset('领证纪念日', true)">领证纪念日</el-button>
          </div>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ isEdit ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, ArrowLeft, Plus } from '@element-plus/icons-vue'
import { getAnniversaryList, createAnniversary, updateAnniversary, deleteAnniversary, getUpcomingAnniversaries } from '@/api'

const router = useRouter()

const loading = ref(false)
const anniversaryList = ref([])
const upcomingList = ref([])

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const submitting = ref(false)

const form = reactive({
  id: null,
  title: '',
  date: '',
  isAnnual: true
})

const rules = {
  title: [
    { required: true, message: '请输入纪念日名称', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ]
}

// 加载纪念日列表
const loadAnniversaryList = async () => {
  loading.value = true
  try {
    const res = await getAnniversaryList()
    if (res.code === 200) {
      anniversaryList.value = res.data || []
    } else {
      ElMessage.error(res.msg || '加载纪念日列表失败')
    }
  } catch (error) {
    console.error('加载纪念日列表失败：', error)
    ElMessage.error('加载纪念日列表失败')
  } finally {
    loading.value = false
  }
}

// 加载即将到来的纪念日
const loadUpcomingAnniversaries = async () => {
  try {
    const res = await getUpcomingAnniversaries()
    if (res.code === 200) {
      upcomingList.value = res.data || []
    }
  } catch (error) {
    console.error('加载即将到来的纪念日失败：', error)
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  form.id = null
  form.title = ''
  form.date = ''
  form.isAnnual = true
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (item) => {
  isEdit.value = true
  form.id = item.id
  form.title = item.title
  form.date = item.date
  form.isAnnual = item.isAnnual
  dialogVisible.value = true
}

// 使用预设
const usePreset = (title, isAnnual) => {
  form.title = title
  form.isAnnual = isAnnual
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let res
        if (isEdit.value) {
          res = await updateAnniversary(form.id, {
            title: form.title,
            date: form.date,
            isAnnual: form.isAnnual
          })
        } else {
          res = await createAnniversary({
            title: form.title,
            date: form.date,
            isAnnual: form.isAnnual
          })
        }
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功！' : '添加成功！')
          dialogVisible.value = false
          loadAnniversaryList()
          loadUpcomingAnniversaries()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('操作失败：', error)
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除纪念日
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个纪念日吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteAnniversary(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadAnniversaryList()
      loadUpcomingAnniversaries()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取图标
const getIcon = (title) => {
  if (title.includes('生日')) return '🎂'
  if (title.includes('恋爱') || title.includes('纪念')) return '💕'
  if (title.includes('见面')) return '👫'
  if (title.includes('领证') || title.includes('结婚')) return '💍'
  return '🎉'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${month}月${day}日`
}

// 获取倒计时
const getCountdown = (dateStr, isAnnual) => {
  if (!dateStr) return ''
  
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  
  let targetDate = new Date(dateStr)
  
  // 如果是每年重复，计算今年的日期
  if (isAnnual) {
    targetDate = new Date(today.getFullYear(), targetDate.getMonth(), targetDate.getDate())
    
    // 如果今年的日期已过，则计算明年的日期
    if (targetDate < today) {
      targetDate.setFullYear(targetDate.getFullYear() + 1)
    }
  }
  
  const diffTime = targetDate - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '🎉 就是今天！'
  } else if (diffDays > 0) {
    return `还有 ${diffDays} 天`
  } else if (isAnnual) {
    // 已过去，计算明年
    targetDate.setFullYear(targetDate.getFullYear() + 1)
    const newDiffTime = targetDate - today
    const newDiffDays = Math.ceil(newDiffTime / (1000 * 60 * 60 * 24))
    return `还有 ${newDiffDays} 天`
  } else {
    return '已过去'
  }
}

onMounted(() => {
  loadAnniversaryList()
  loadUpcomingAnniversaries()
})

// 返回主页
const goHome = () => {
  router.push('/home')
}
</script>

<style scoped>
.anniversary-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding-bottom: 20px;
}

/* 顶部标题栏 */
.page-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: linear-gradient(135deg, #ff85c0 0%, #ff69b4 100%);
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.2);
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  flex: 1;
  text-align: center;
}

.back-btn,
.add-btn {
  background: rgba(255, 255, 255, 0.3);
  border: none;
  color: white;
  width: 36px;
  height: 36px;
}

.back-btn:hover,
.add-btn:hover {
  background: rgba(255, 255, 255, 0.5);
}

.section-title {
  margin: 0 0 16px 0;
  padding: 0 16px;
  color: #666;
  font-size: 18px;
  font-weight: 600;
}

.upcoming-section {
  margin: 16px 0 24px;
}

.upcoming-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
  padding: 0 16px;
}

.all-section {
  margin-top: 24px;
}

.anniversary-list {
  padding: 0 16px;
}

.anniversary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

.anniversary-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(255, 105, 180, 0.1);
  transition: all 0.3s ease;
}

.anniversary-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(255, 105, 180, 0.2);
}

.anniversary-card:active {
  transform: scale(0.98);
}

.anniversary-card.upcoming {
  background: linear-gradient(135deg, #fff5f7 0%, #ffe5f1 100%);
  border: 2px solid #ff69b4;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-icon {
  font-size: 40px;
  margin-bottom: 8px;
}

.card-actions {
  display: flex;
  gap: 6px;
}

.card-actions .el-button {
  width: 32px;
  height: 32px;
}

.card-content {
  text-align: center;
}

.card-title {
  margin: 0 0 8px 0;
  font-size: 17px;
  font-weight: bold;
  color: #333;
}

.card-date {
  margin: 0 0 8px 0;
  font-size: 15px;
  color: #666;
}

.card-type {
  margin: 8px 0;
}

.countdown {
  margin: 12px 0 0 0;
  font-size: 18px;
  font-weight: bold;
  color: #ff69b4;
}

.empty-state {
  padding: 60px 0;
}

.quick-presets {
  margin-top: 20px;
  padding: 15px;
  background: #ffeef8;
  border-radius: 8px;
}

.preset-title {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
}

.preset-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    font-size: 18px;
  }

  .section-title {
    font-size: 16px;
  }

  .anniversary-grid,
  .upcoming-cards {
    grid-template-columns: 1fr;
  }

  .anniversary-card {
    padding: 16px;
  }

  .card-icon {
    font-size: 36px;
  }

  .card-title {
    font-size: 16px;
  }

  .card-date {
    font-size: 14px;
  }

  .countdown {
    font-size: 16px;
  }

  .card-actions .el-button {
    width: 28px;
    height: 28px;
  }
}

/* 平板及以上 */
@media (min-width: 768px) {
  .anniversary-container {
    padding-bottom: 40px;
  }

  .upcoming-section,
  .all-section {
    max-width: 1000px;
    margin-left: auto;
    margin-right: auto;
  }

  .section-title {
    padding: 0 24px;
  }

  .upcoming-cards,
  .anniversary-list {
    padding: 0 24px;
  }

  .anniversary-grid,
  .upcoming-cards {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
  }

  .anniversary-card {
    padding: 24px;
  }

  .card-icon {
    font-size: 48px;
  }
}
</style>

